package com.ranqianhui.ojbackendjudgeservice;

import cn.hutool.json.JSONUtil;

import com.ranqianhui.ojbackendcommon.common.ErrorCode;
import com.ranqianhui.ojbackendcommon.exception.BusinessException;
import com.ranqianhui.ojbackendjudgeservice.codesandbox.CodeSandbox;
import com.ranqianhui.ojbackendjudgeservice.codesandbox.CodeSandboxFactory;
import com.ranqianhui.ojbackendjudgeservice.codesandbox.CodeSandboxProxy;
import com.ranqianhui.ojbackendjudgeservice.strategy.JudgeContext;
import com.ranqianhui.ojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import com.ranqianhui.ojbackendmodel.model.codesandbox.ExecuteCodeResponse;
import com.ranqianhui.ojbackendmodel.model.codesandbox.JudgeInfo;
import com.ranqianhui.ojbackendmodel.model.dto.question.JudgeCase;
import com.ranqianhui.ojbackendmodel.model.entity.Question;
import com.ranqianhui.ojbackendmodel.model.entity.QuestionSubmit;
import com.ranqianhui.ojbackendmodel.model.enums.QuestionSubmitStatusEnum;
import com.ranqianhuii.ojbackendserviceclient.service.QuestionClient;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class JudgeServiceImpl implements JudgeService {

    private final QuestionClient questionClient;

    private final JudgeManager judgeManager;

    @Value("${codesandbox.type}")
    private String type;
    @Override
    public QuestionSubmit doJudge(Long questionSubmitId) {
//        1）传入题目的提交 id，获取到对应的题目、提交信息（包含代码、编程语言等）
        QuestionSubmit questionSubmit=questionClient.getQuestionSubmitById(questionSubmitId);
        if (questionSubmitId==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question=questionClient.getQuestionById(questionId);
        if (question==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"题目不存在");
        }
//        2）如果题目提交状态不为等待中，就不用重复执行了，业务幂等

        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"正在判题中");
        }
        //3）更改判题（题目提交）的状态为 “判题中”，防止重复执行，也能让用户即时看到状态
        QuestionSubmit questionSubmitUpdate=new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionClient.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新错误");
        }
//        4）调用沙箱，获取到执行结果
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox=new CodeSandboxProxy(codeSandbox);
        //获取输入用例
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList= JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList= judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        //获取提交的代码和编译语言
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        List<String> outputList = executeCodeResponse.getOutputList();
//        5）根据沙箱的执行结果，设置题目的判题状态和信息 判断逻辑
        JudgeContext judgeContext=new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo judgeInfo= judgeManager.doJudge(judgeContext);
        //修改数据库中的判题结果
        questionSubmitUpdate=new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
       update = questionClient.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新错误");
        }
        QuestionSubmit questionSubmitResult = questionClient.getQuestionSubmitById(questionSubmitId);
        return questionSubmitResult;
    }
}
